<template>

  <ContentWrap :title="device.deviceName+': '+device.code">
    <!-- 搜索工作栏 -->
    <el-button type="primary" @click="handleReuse">
      复用
    </el-button>
  </ContentWrap>
  <ContentWrap>
    <!-- 新增进度条和提交按钮 -->
    <el-row :gutter="20" align="middle" class="mb-4">
      <el-col :span="18">
        <el-progress
            :percentage="process"
        />
      </el-col>
      <el-col :span="6" class="text-right">
        <el-button
            type="primary"
            :disabled="process < 100 || identifyInstance.status !=0 "
            @click="handleSubmit"
        >
          提交评估
        </el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData">
      <el-table-column prop="riskTarget" label="风险对象"/>
      <el-table-column prop="identifyContent" label="辨识内容"/>
      <el-table-column prop="identifyContentCode" label="辨识内容编码"/>
      <el-table-column prop="hazard" label="危害"/>
      <el-table-column prop="projectSolution" label="工程解决方案"/>
      <el-table-column prop="managerSolution" label="管理解决方案"/>
      <el-table-column prop="selfSolution" label="个人解决方案"/>
      <el-table-column prop="trainEduSolution" label="培训教育解决方案"/>
      <el-table-column label="风险等级">
        <template #default="scope">
          <el-button :value="scope.row.riskLevel" :type="riskLevelClassType[scope.row.riskLevel]"
                     v-if="scope.row.riskLevel">
            {{ riskLevelDict[scope.row.riskLevel] }}
          </el-button>
        </template>
      </el-table-column>
      <!-- 新增两个风险等级列 -->
      <el-table-column label="固定风险等级">
        <template #default="scope">
          <el-button :value="scope.row.fixedRiskLevel" :type="riskLevelClassType[scope.row.fixedRiskLevel]"
                     v-if="scope.row.fixedRiskLevel">
            {{ riskLevelDict[scope.row.fixedRiskLevel] }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="实际风险等级">
        <template #default="scope">
          <el-button :value="scope.row.realRiskLevel" :type="riskLevelClassType[scope.row.realRiskLevel]"
                     v-if="scope.row.realRiskLevel">
            {{ riskLevelDict[scope.row.realRiskLevel] }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="风险度">
        <template #default="scope">
          <div class="flex gap-5" v-if="scope.row.riskDegree.l">
            {{ scope.row.riskDegree.r }} = {{ scope.row.riskDegree.l }} * {{ scope.row.riskDegree.s }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="supplementSuggest" label="补充建议"/>
      <!-- 新增操作列 -->
      <el-table-column label="操作" align="center" fixed="right" width="120">
        <template #default="scope">
          <el-button
              type="primary"
              link
              @click="handleAssess(scope.row)"
          >
            评估
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <el-dialog
      v-model="dialogVisible"
      :title="`风险评估`"
      width="80%"
  >
    <!-- 新增步骤条 -->
    <el-steps :active="activeStep" align-center class="mb-4">
      <el-step title="解决方案" :status="'success'"/>
      <el-step title="风险评估" :status="currentRow.riskDegree.l?'success':''"/>
      <el-step title="风险管控" :status="currentRow.checkContents?.length>0?'success':''"/>
    </el-steps>

    <el-form label-width="120px" :rules="rules" ref="formRef" :model="currentRow">
      <!-- 基础信息 -->
      <!-- 新增折叠面板 -->
      <div class="flex">
        <el-form-item label="风险对象" prop="riskTarget">
          <el-input v-model="currentRow.riskTarget" disabled/>
        </el-form-item>
        <el-form-item label="辨识内容" prop="identifyContent">
          <el-input v-model="currentRow.identifyContent" disabled/>
        </el-form-item>
      </div>
      <el-collapse v-model="activeCollapse" class="mb-4" expand-icon-position="left">
        <el-collapse-item title="解决方案" name="solutions">
          <el-form-item label="危害" prop="hazard">
            <el-input
                v-model="currentRow.hazard"
                :autosize="{ minRows: 3 }"
                type="textarea"
            />
          </el-form-item>
          <el-form-item label="工程解决方案" prop="projectSolution">
            <el-input
                v-model="currentRow.projectSolution"
                :autosize="{ minRows: 3 }"
                type="textarea"
            />
          </el-form-item>
          <el-form-item label="管理解决方案" prop="managerSolution">
            <el-input
                v-model="currentRow.managerSolution"
                :autosize="{ minRows: 3 }"
                type="textarea"
            />
          </el-form-item>
          <el-form-item label="个人解决方案" prop="selfSolution">
            <el-input
                v-model="currentRow.selfSolution"
                :autosize="{ minRows: 2 }"
                type="textarea"
            />
          </el-form-item>
          <el-form-item label="培训解决方案" prop="trainEduSolution">
            <el-input
                v-model="currentRow.trainEduSolution"
                :autosize="{ minRows: 2 }"
                type="textarea"
            />
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item title="风险评估" name="riskLevels">
          <el-form-item label="风险度" style="width: 100%">
            <div class="flex flex-col w-full">
              <div class="flex riskDegree gap-5 pb-3">
                <el-form-item prop="riskDegree.l" style="width: 200px">
                  <el-input
                      v-model.number="currentRow.riskDegree.l"
                      placeholder="L值"
                      :min="1"
                      :max="5"
                      type="number"
                      @input="currentRow.riskDegree.r = currentRow.riskDegree.l * currentRow.riskDegree.s"
                  />
                </el-form-item>
                <el-form-item prop="riskDegree.s" style="width: 200px">
                  <el-input
                      v-model.number="currentRow.riskDegree.s"
                      placeholder="S值"
                      :min="1"
                      :max="5"
                      type="number"
                      @input="currentRow.riskDegree.r = currentRow.riskDegree.l * currentRow.riskDegree.s"
                  />
                </el-form-item>
                <el-form-item prop="riskDegreeR" style="width: 200px">
                  <el-input
                      v-model.number="currentRow.riskDegree.r"
                      placeholder="R值"
                      readonly
                  />
                </el-form-item>

              </div>
              <div class="text-sm text-gray-400 mt-1">风险度计算采用SCL表标准：R = L（可能性） ×
                S（严重程度）
              </div>
            </div>
          </el-form-item>
          <el-form-item label="动态风险">
            <div class="flex gap-2" prop="riskLevel">
              <el-radio-group v-model="currentRow.riskLevel">
                <el-button
                    :class="{ 'is-active': currentRow.riskLevel === '1', 'el-button--primary': true }"
                >
                  低风险
                </el-button>
                <el-button
                    :class="{ 'is-active': currentRow.riskLevel === '2', 'el-button--info': true }"
                >
                  一般风险
                </el-button>
                <el-button
                    :class="{ 'is-active': currentRow.riskLevel === '3', 'el-button--warning': true }"
                >
                  较大风险
                </el-button>
                <el-button
                    :class="{ 'is-active': currentRow.riskLevel === '4', 'el-button--danger': true }"
                >
                  重大风险
                </el-button>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item label="固定风险" prop="fixedRiskLevel">
            <div class="flex gap-2">
              <el-radio-group v-model="currentRow.fixedRiskLevel">
                <el-button
                    :class="{ 'is-active': currentRow.fixedRiskLevel === '1', 'el-button--primary': true }"
                    @click="currentRow.fixedRiskLevel = '1'"
                >
                  低风险
                </el-button>
                <el-button
                    :class="{ 'is-active': currentRow.fixedRiskLevel === '2', 'el-button--info': true }"
                    @click="currentRow.fixedRiskLevel = '2'"
                >
                  一般风险
                </el-button>
                <el-button
                    :class="{ 'is-active': currentRow.fixedRiskLevel === '3', 'el-button--warning': true }"
                    @click="currentRow.fixedRiskLevel = '3'"
                >
                  较大风险
                </el-button>
                <el-button
                    :class="{ 'is-active': currentRow.fixedRiskLevel === '4', 'el-button--danger': true }"
                    @click="currentRow.fixedRiskLevel = '4'"
                >
                  重大风险
                </el-button>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item label="实际风险" prop="realRiskLevel">
            <el-button :value="currentRow.realRiskLevel" :type="riskLevelClassType[currentRow.realRiskLevel]"
                       v-if="currentRow.realRiskLevel">
              {{ riskLevelDict[currentRow.realRiskLevel] }}
            </el-button>
          </el-form-item>

          <el-form-item label="补充建议" prop="supplementSuggest">
            <el-input
                v-model="currentRow.supplementSuggest"
                :autosize="{ minRows: 2 }"
                type="textarea"
            />
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item title="风险管控" name="riskManager">
          <el-form-item label="所属单元" prop="unitId">
            <el-tree-select
                v-model="currentRow.riskTargetContentUnitId"
                :data="unitTree"
                :props="defaultProps"
                check-strictly
                default-expand-all
                placeholder="请选择部门"
                value-key="deptId"
            />
          </el-form-item>
          <el-form-item label="单元负责人" prop="riskTargetContentLeaderId">
            <el-select v-model="currentRow.riskTargetContentLeaderId" clearable placeholder="请选择所属人">
              <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检查周期" prop="checkCycle">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-input
                    v-model.number="currentRow.checkCycle.number"
                    placeholder="请输入数字"
                    type="number"
                />
              </el-col>
              <el-col :span="12">
                <el-select v-model="currentRow.checkCycle.unit" placeholder="请选择">
                  <el-option label="天" value="day"/>
                  <el-option label="周" value="week"/>
                  <el-option label="月" value="month"/>
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="检查内容" prop="checkContents">
            <div class="flex flex-col w-80%">
              <div v-for="(item, index) in currentRow.checkContents" :key="index" class="mb-2">
                <div class="w-4/5">
                  <el-input
                      v-model="currentRow.checkContents[index]"
                      :autosize="{ minRows: 1 }"
                      type="textarea"
                      placeholder="请输入检查内容"
                  />
                  <el-button
                      type="danger"
                      link
                      @click="currentRow.checkContents.splice(index, 1)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
            <el-button
                type="primary"
                link
                @click="currentRow.checkContents.push('')"
            >
              + 添加检查内容
            </el-button>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <!-- 在弹窗底部添加操作按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="sure">确定</el-button>
        <el-button
            @click="switchRow(-1)"
        >上一个
        </el-button>
        <el-button
            @click="switchRow(1)"
        >下一个
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
      v-model="reuseDialogVisible"
      title="选择评估记录"
  >
    <el-table :data="reuseData">
      <el-table-column prop="deviceCode" label="设备实例编码" width="180"/>
      <el-table-column prop="assessor" label="评估人" width="120"/>
      <el-table-column prop="assessTime" label="评估时间" width="200"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" link @click="adoptAssessment(scope.row)">
            采用
          </el-button>
          <el-button type="primary" link>
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

</template>

<script setup lang="ts">
import {onMounted, ref, computed} from 'vue';
import {ElMessage, FormInstance} from 'element-plus';
import {RiskIdentifyTargetApi} from "@/api/zjyj/riskidentifytarget";
import {RiskIdentifyInstanceApi} from "@/api/zjyj/riskidentifyinstance";
import {riskLevelClassType, riskLevelDict} from "@/views/zjyj/riskAssessment/dict";
import {RiskLevelConfApi} from "@/api/zjyj/risklevelconf";
import {defaultProps, handleTree} from "@/utils/tree";
import {TenantUnitApi} from "@/api/zjyj/tenantunit";
import * as UserApi from "@/api/system/user";
import {RiskAssessmentRecordApi} from "@/api/zjyj/riskassessmentrecord";

defineOptions({
  name: 'DeviceAssessment',
});

const props = defineProps({
  applyRecordId: {
    type: Number,
    required: true,
  },
  identifyInstanceId: {
    type: Number,
    required: true,
  },
})

const userList = ref<UserApi.UserVO[]>([]); // 用户列表

const reuseDialogVisible = ref(false);
const reuseData = ref([
  {
    deviceCode: 'DEV-2024-001',
    assessor: '张三',
    assessTime: '2024-03-15 14:30:00',
    data: {/* 完整评估数据 */}
  },
  {
    deviceCode: 'DEV-2024-002',
    assessor: '李四',
    assessTime: '2024-03-16 09:45:00',
    data: {/* 完整评估数据 */}
  }
]);

const message = useMessage(); // 消息弹窗

const process = ref(0);

const adoptAssessment = (row: any) => {
  // 这里实现采用评估记录的逻辑
  ElMessage.success('评估记录已采用');
  dialogVisible.value = false;
};
// 新增响应式数据
const dialogVisible = ref(false);
const currentRow = ref({
  // 基础信息
  riskTarget: '',
  identifyContent: '',
  identifyContentCode: '',

  // 解决方案
  hazard: '',
  projectSolution: '',
  managerSolution: '',
  selfSolution: '',
  trainEduSolution: '',

  // 风险评估
  riskLevel: '',
  fixedRiskLevel: '',
  actualRiskLevel: '',
  riskDegree: {
    l: null,
    s: null,
    r: null
  },
  supplementSuggest: '',

  // 风险管控
  riskTargetContentUnitId: '',
  riskTargetContentLeaderId: '',
  checkCycle: {
    number: 0,
    unit: 'day'
  },
  checkContents: []
});


const switchRow = async (direction) => {
  const index = tableData.value.findIndex(item => item.contentId === currentRow.value.contentId)
  const newIndex = index + direction
  console.log('switchRow', index, newIndex, currentRow.value)
  if (newIndex < 0) {
    message.info('已经是第一个了')
    return
  } else if (newIndex >= tableData.value.length) {
    message.info('已经是最后一个了')
    return
  }
  await formRef.value?.validate((valid) => {
    if (valid) {
      handleDialogSubmit()
      refreshCurrentRow()
      const data = tableData.value[newIndex]
      currentRow.value = {
        ...data,
        checkCycle: {
          number: data.checkCycle?.number || 0,
          unit: data.checkCycle?.unit || 'day'
        },
        checkContents: data?.checkContents||[]
      }
    } else {
      message.info('请先保存当前数据后再切换')
    }
  })
};

const rules = reactive({
  riskTarget: [{required: true, message: '风险对象不能为空', trigger: 'blur'}],
  identifyContent: [{required: true, message: '辨识内容不能为空', trigger: 'blur'}],
  hazard: [{required: true, message: '危害不能为空', trigger: 'blur'}],
  projectSolution: [{required: true, message: '工程解决方案不能为空', trigger: 'blur'}],
  managerSolution: [{required: true, message: '管理解决方案不能为空', trigger: 'blur'}],
  selfSolution: [{required: true, message: '个人解决方案不能为空', trigger: 'blur'}],
  trainEduSolution: [{required: true, message: '培训教育解决方案不能为空', trigger: 'blur'}],
  riskDegree: {
    l: [{required: true, message: 'L值不能为空', trigger: 'blur'}],
    s: [{required: true, message: 'S值不能为空', trigger: 'blur'}],
  },
  riskLevel: [{required: true, message: '风险等级不能为空', trigger: 'blur'}],
  fixedRiskLevel: [{required: true, message: '固定风险等级不能为空', trigger: 'blur'}],
  supplementSuggest: [{required: true, message: '补充建议不能为空', trigger: 'blur'}],
  riskTargetContentUnitId: [{required: true, message: '所属单元不能为空', trigger: 'blur'}],
  riskTargetContentLeaderId: [{required: true, message: '单元负责人不能为空', trigger: 'blur'}],
  checkCycle: [{required: true, message: '检查周期不能为空', trigger: 'blur'}],
  checkContents: [{required: true, message: '检查内容不能为空', trigger: 'blur'}],
})

const unitTree = ref() // 树形结构

// 评估按钮点击处理
const handleAssess = (row) => {
  try {
    // 初始化当前行数据
    currentRow.value = {
      ...row,
      checkCycle: {
        number: row.checkCycle?.number || 0,
        unit: row.checkCycle?.unit || 'day'
      },
      checkContents: row?.checkContents||[]
    };
    // 打开弹窗
    dialogVisible.value = true;
  } catch (error) {
    // 处理可能出现的错误
    ElMessage.error('打开评估弹窗失败，请稍后重试');
  }
};

const handleReuse = () => {
  reuseDialogVisible.value = true;
};

// Mock 数据（模拟锅炉设备风险评估数据）
const tableData = ref<any>([]);

const formRef = ref<FormInstance>()

const activeStep = computed(() => {
  const lastActive = activeCollapse.value[activeCollapse.value.length - 1]
  const stepMap = {'solutions': 0, 'riskLevels': 1, 'riskManager': 2}
  return stepMap[lastActive] || 0
});

const device = ref({})

const identifyInstance = ref({})
// 新增提交处理
const handleDialogSubmit = () => {
  const index = tableData.value.findIndex(item => item.contentId === currentRow.value.contentId)
  if (index !== -1) {
    tableData.value[index] = {...currentRow.value}
  }
};


const getIdentifyInstance = async () => {
  const res = await RiskIdentifyInstanceApi.getRiskIdentifyInstance(props.identifyInstanceId)
  identifyInstance.value = res
}
const handleSubmit = async () => {
  await message.confirm(`确认是否评估`)
  await RiskAssessmentRecordApi.submitAssessment({
    applyRecordId:Number(props.applyRecordId),
    identifyInstanceId:Number(props.identifyInstanceId),
    contents:tableData.value
  })
  await message.success('评估成功')

};
const getDevice = async () => {
  device.value = await RiskIdentifyInstanceApi.getDeviceInstanceByIdentifyInstanceId(props.identifyInstanceId)
}

const getContents = async () => {
  const targets = await RiskIdentifyTargetApi.getRiskIdentifyTargetByIdentifyInstanceId(props.identifyInstanceId);
  targets.forEach(target => {
    target.contents.forEach(content => {
      tableData.value.push({
        "contentId": content.id,
        "riskTarget": target.riskTarget,
        "identifyContent": content.identifyContent,
        "identifyContentCode": content.identifyContentCode,
        "hazard": content.hazard,
        "projectSolution": content.projectSolution,
        "managerSolution": content.managerSolution,
        "selfSolution": content.selfSolution,
        "trainEduSolution": content.trainEduSolution,
        "riskLevel": content.riskLevel,
        "fixedRiskLevel": content.fixedRiskLevel,
        "actualRiskLevel": content.actualRiskLevel,
        "riskDegree": {
          "l": content.riskDegree?.l,
          "s": content.riskDegree?.s,
          "r": content.riskDegree?.r
        },
        "supplementSuggest": content.supplementSuggest,
        "riskTargetContentUnitId": content.riskTargetContentUnitId ?? device.value?.unitId,
        "riskTargetContentLeaderId": content.riskTargetContentLeaderId ?? device.value?.ownerId
      });
    });
  })
}

const sure = async () => {
  await formRef.value?.validate((valid) => {
    if (valid) {
      handleDialogSubmit();
      dialogVisible.value = false;
    }
  })
  // 判断formRef的规则都符合
}

const refreshCurrentRow = async () => {
  // 表单校验刷新
  formRef.value?.clearValidate();
  currentRow.value = {
    // 基础信息
    riskTarget: '',
    identifyContent: '',
    identifyContentCode: '',

    // 解决方案
    hazard: '',
    projectSolution: '',
    managerSolution: '',
    selfSolution: '',
    trainEduSolution: '',

    // 风险评估
    riskLevel: '',
    fixedRiskLevel: '',
    actualRiskLevel: '',
    riskDegree: {
      l: null,
      s: null,
      r: null
    },
    supplementSuggest: '',

    // 风险管控
    riskTargetContentUnitId: '',
    riskTargetContentLeaderId: '',
    checkCycle: {
      number: 0,
      unit: 'day'
    },
    checkContents: []
  }
}


// 定义计算 realRiskLevel 的函数，这里简单取两者最大值作为示例，可按需修改
const calculateRealRiskLevel = (fixedRiskLevel: string, riskLevel: string) => {
  return Math.max(Number(fixedRiskLevel), Number(riskLevel)).toString();
};
const riskLevelConf = ref({})

const getRiskLevelConf = async () => {
  const data = await RiskLevelConfApi.getRiskLevelConfPage({"pageNo": 1, "pageSize": 1, "riskType": 2})
  riskLevelConf.value = data.list[0]
};

const countProcess = () => {
  const total = tableData.value.length
  const completed = tableData.value.filter(item => item.realRiskLevel > 0).length
  process.value = total === 0 ? 0 : Math.round((completed / total) * 100)
}

watch(
    [() => currentRow.value.fixedRiskLevel, () => currentRow.value.riskLevel],
    ([newFixedRiskLevel, newRiskLevel]) => {
      if (newFixedRiskLevel && newRiskLevel) {
        currentRow.value.realRiskLevel = calculateRealRiskLevel(newFixedRiskLevel, newRiskLevel);
      }
    }
);

watch(() => dialogVisible.value, (nv, _ov) => {
  if (nv == false) {
    refreshCurrentRow();
    countProcess();
  }
}, {deep: true})
watch(() => currentRow.value.riskDegree, (newRiskDegree) => {
  if (!Number.isNaN(newRiskDegree.r)) {
    // 判断 newRiskDegree.r是在哪个区间内
    if (newRiskDegree.r >= riskLevelConf.value.lowLevelMinValue && newRiskDegree.r <= riskLevelConf.value.lowLevelMaxValue) {
      currentRow.value.riskLevel = "1"
    } else if (newRiskDegree.r >= riskLevelConf.value.generalLevelMinValue && newRiskDegree.r <= riskLevelConf.value.generalLevelMaxValue) {
      currentRow.value.riskLevel = "2"
    } else if (newRiskDegree.r >= riskLevelConf.value.largerLevelMinValue && newRiskDegree.r <= riskLevelConf.value.largerLevelMaxValue) {
      currentRow.value.riskLevel = "3"
    } else if (newRiskDegree.r >= riskLevelConf.value.majorLevelMinValue && newRiskDegree.r <= riskLevelConf.value.majorLevelMaxValue) {
      currentRow.value.riskLevel = "4"
    }
  }
}, {deep: true});
// 在 script setup 部分添加
const activeCollapse = ref(['basic', 'solutions']); // 默认展开所有面板

onMounted(async () => {
  // 模拟从后端获取数据
  await getDevice()
  await getIdentifyInstance()
  await getContents()
  await getRiskLevelConf()
  unitTree.value = handleTree(await TenantUnitApi.getSimpleUnitList())
  userList.value = await UserApi.getSimpleUserList();
})

</script>


<style scoped>
.el-button.is-active {
  /* 自定义选中状态样式 */
  outline: 2px solid #409EFF;
  /* 增加外边框距，避免边框覆盖按钮内容 */
  outline-offset: 1px;
  /* 去除默认的 box-shadow，避免样式冲突 */
  box-shadow: none;
}
</style>
